package server.utils;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.core.annotation.Order;
import org.springframework.web.util.WebUtils;

@Order(1)
@WebFilter(filterName = "filter1", urlPatterns = "/*")
public class FetchSession implements javax.servlet.Filter{

    private static final String regex=".*(css|html|ico|html|jpg|jpeg|png|gif|js|ico)";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private static String getSessionId(ServletRequest request){
        HttpServletRequest httpRequest=(HttpServletRequest)request;
        String sessionId="";
        Cookie cookie =WebUtils.getCookie(httpRequest, "PHPSESSID");
        if(cookie!=null){
            return cookie.getValue();
        }
        cookie =WebUtils.getCookie(httpRequest, "JSESSIONID");
        if(cookie!=null){
            sessionId= cookie.getValue();
        }
        return sessionId;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        String sessionId="123456";
        HttpServletRequest httpRequest=(HttpServletRequest)request;
        String requestedUri=httpRequest.getRequestURL().toString();
        System.out.println(requestedUri);
//        if(requestedUri.matches(regex)){
//            chain.doFilter(request, response);
//            return;
//        }
        GetSessionWrapper wrapperRequest=new GetSessionWrapper(httpRequest,sessionId);
        //HttpSession httpSession=wrapperRequest.getSession();
        chain.doFilter(wrapperRequest, response);
    }

    @Override
    public void destroy() {
    }
}
